<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Libraries\Small\WxSmallService;
use App\Model\WebUserModel;
use Illuminate\Http\Request;
class QrcodeController extends Controller{


    //签到二维码
    public function index(Request $request){
        $uuid = $request->input('uuid');
        $type = $request->input('type');
        $path = $request->input('path');

        if(!isset($uuid) || empty($uuid)){
            return response()->json(array('code' => 400,'message' => 'uuid值不能为空'));
        }

        if(!isset($path) || empty($path)){
            return response()->json(array('code' => 400,'message' => '请传跳转路径'));
        }

        if(!isset($type) || empty($type)){
            return response()->json(array('code' => 400,'message' => '请传二维码类型'));
        }

        $user_data = WebUserModel::where('iUUID',$uuid)->first();
        if(!$user_data){
            return response()->json(array('code' => 400,'message' => '该用户不存在'));
        }

        if($user_data->type != 1){
            return response()->json(array('code' => 400,'message' => '该用户不是商户'));
        }

        $path_name = '/usr/local/nginx/html/xinmo_master/public';
        //签到
        if($type == 1){

            $file_name = '/image/qrcode/sign/'.date('Ymd').'.png';
            $filetem = $path_name.$file_name;
            if(file_exists($filetem)){
                return response()->json(array('code' => 200,'message' => '成功','data'=>['src'=>$_SERVER['SERVER_NAME'].$file_name]));
            }
        }else{ //兑换

            $file_name = '/image/qrcode/merchants/'.date('Ymd').'.png';
            $filetem=$path_name.$file_name;

            if(file_exists($filetem)){
                return response()->json(array('code' => 200,'message' => '成功','data'=>['src'=>$_SERVER['SERVER_NAME'].$file_name]));
            }
        }

        //获取微信的access——token
        $get_access_token = WxSmallService::get_access_token();
        if($get_access_token['code'] == 200){
            $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$get_access_token['data']['access_token'];
            $option_json = json_encode([
                'path'       => $path,
                'auto_color' => false,
                'line_color' => (object)['r'=>0,'g'=>0,'b'=>0],
                'is_hyaline' => false,
                'width'      => '430'
            ]);
            $src_data = WxSmallService::api_notice_increment($url,$option_json);


            $file = $path_name.$file_name;
            file_put_contents($file,$src_data);

            return response()->json(array('code' => 200,'message' => '成功','data'=>['src'=>$_SERVER['SERVER_NAME'].$file_name]));

        }else{
            return response()->json(array('code' => 400,'/' => '获取小程序二维码失败'));
        }

    }
}